package loader

import (
	"fmt"
	"path/filepath"
	"kumachan/interpreter/lang/textual/ast"
)

func LoadAssets(root *ast.Root, ref FileRef) {
	for i := range root.Statements {
		var stmt = &(root.Statements[i])
		var asset_info, is_asset = stmt.Statement.(ast.Asset)
		if is_asset {
			var dir = filepath.Dir(ref.Path)
			var asset_rel_path = string(asset_info.Path.Value)
			var asset_path = filepath.Join(dir, asset_rel_path)
			var item_content, err = ReadFile(asset_path, ref.FS)
			var value = (func() ast.ConstValue {
				if err != nil {
					var err = fmt.Errorf("failed to read asset file: %w", err)
					return ast.InvalidAsset {
						Node: asset_info.Path.Node,
						Error: err,
					}
				} else {
					return ast.LoadedAsset {
						Node:  asset_info.Path.Node,
						Path:  asset_path,
						Bytes: item_content,
					}
				}
			})()
			stmt.Statement = ast.DeclConst {
				Node:   asset_info.Node,
				Public: asset_info.Public,
				Name:   asset_info.Name,
				Type:   asset_info.Type,
				Value:  ast.VariousConstValue {
					Node:       asset_info.Node,
					ConstValue: value,
				},
			}
		}
	}
}


